{% extends "base.html" %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="h3 mb-0 text-gray-800">API Dashboard</h1>
        <p class="mb-0">Manage and execute your Python APIs</p>
    </div>
    <a href="/create" class="btn btn-primary">
        <i class="bi bi-plus-circle me-1"></i> Create New API
    </a>
</div>

<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-primary shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                            Total APIs
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ apis|length }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-boxes fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-success shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                            Total Functions
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ total_functions }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-code-square fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-info shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                            API Prefix
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ api_prefix }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-link-45deg fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card border-left-warning shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                            API Keys
                        </div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ api_keys_count }}</div>
                    </div>
                    <div class="col-auto">
                        <i class="bi bi-key fa-2x text-gray-300"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

{% if apis %}
<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">Your APIs</h6>
        <div>
            <button class="btn btn-sm btn-outline-success me-2" onclick="enableBatchExport()">
                <i class="bi bi-download me-1"></i> Batch Export
            </button>
            <a href="/api/import" class="btn btn-sm btn-outline-primary">
                <i class="bi bi-upload me-1"></i> Import
            </a>
        </div>
    </div>
    <div class="card-body">

        <!-- 添加批量操作工具栏 -->
        <div id="batchToolbar" class="d-none mb-3 p-3 bg-light rounded">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <span id="selectedCount">0</span> APIs selected
                </div>
                <div>
                    <button class="btn btn-sm btn-success me-2" onclick="exportSelectedAPIs()">
                        <i class="bi bi-download me-1"></i> Export Selected
                    </button>
                    <button class="btn btn-sm btn-secondary" onclick="disableBatchExport()">
                        Cancel
                    </button>
                </div>
            </div>
        </div>

        <div class="row">
            {% for api_id, api in apis.items() %}
              <div class="col-md-6 col-lg-4 mb-4">
                <div class="card api-card h-100">
                    <div class="card-header">
                        <div class="form-check batch-select d-none">
                            <input class="form-check-input" type="checkbox" value="{{ api_id }}"
                                   onchange="updateSelectionCount()">
                        </div>
                        <h5 class="card-title mb-0">{{ api.name }}</h5>
                        <small class="text-muted">ID: {{ api_id }}</small>
                    </div>
                    <div class="card-body">
                        <p class="card-text">{{ api.description|default('No description', true) }}</p>

                        <div class="mb-3">
                            <span class="badge bg-info me-1">
                                {{ api.functions|length }} function{{ '' if api.functions|length == 1 else 's' }}
                            </span>
                            <span class="badge bg-secondary me-1">
                                Created: {{ api.created_at|default('N/A', true) }}
                            </span>
                            {% if api.updated_at %}
                            <span class="badge bg-secondary">
                                Updated: {{ api.updated_at }}
                            </span>
                            {% endif %}
                        </div>

                        <div class="mb-3">
                            <strong>Functions:</strong>
                            <div class="mt-2 d-flex flex-wrap gap-1">
                                {% for func_name, func in api.functions.items() %}
                                <span class="badge bg-primary function-badge"
                                      data-bs-toggle="tooltip" title="{{ func.description|default('No description', true) }}">
                                    {{ func_name }}
                                </span>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                    <div class="card-footer bg-transparent d-flex justify-content-between">
                        <a href="/api/{{ api_id }}" class="btn btn-sm btn-outline-primary">
                            <i class="bi bi-eye"></i> View
                        </a>
                        <a href="/api/{{ api_id }}/edit" class="btn btn-sm btn-outline-secondary">
                            <i class="bi bi-pencil"></i> Edit
                        </a>
                        <form action="/api/{{ api_id }}/delete" method="post" class="d-inline">
                            <button type="submit" class="btn btn-sm btn-outline-danger">
                                <i class="bi bi-trash"></i> Delete
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
</div>
{% else %}
<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-primary">No APIs Created</h6>
    </div>
    <div class="card-body text-center py-5">
        <i class="bi bi-box text-primary" style="font-size: 3rem;"></i>
        <h5 class="mt-3">You haven't created any APIs yet</h5>
        <p class="text-muted">Get started by creating your first API to transform Python scripts into web services</p>
        <a href="/create" class="btn btn-primary mt-2">
            <i class="bi bi-plus-circle me-1"></i> Create Your First API
        </a>
    </div>
</div>
{% endif %}
{% endblock %}

{% block scripts %}
<script>
let batchExportMode = false;

function enableBatchExport() {
    batchExportMode = true;
    document.getElementById('batchToolbar').classList.remove('d-none');
    document.querySelectorAll('.batch-select').forEach(el => {
        el.classList.remove('d-none');
    });
}

function disableBatchExport() {
    batchExportMode = false;
    document.getElementById('batchToolbar').classList.add('d-none');
    document.querySelectorAll('.batch-select').forEach(el => {
        el.classList.add('d-none');
    });
    // 取消所有选择
    document.querySelectorAll('.batch-select input[type="checkbox"]').forEach(checkbox => {
        checkbox.checked = false;
    });
    updateSelectionCount();
}

function updateSelectionCount() {
    const selectedCount = document.querySelectorAll('.batch-select input[type="checkbox"]:checked').length;
    document.getElementById('selectedCount').textContent = selectedCount;
}

function exportSelectedAPIs() {
    const selectedAPIs = Array.from(document.querySelectorAll('.batch-select input[type="checkbox"]:checked'))
        .map(checkbox => checkbox.value);

    if (selectedAPIs.length === 0) {
        alert('Please select at least one API to export');
        return;
    }

    fetch('/api/batch_export', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ apis: selectedAPIs })
    })
    .then(response => response.json())
    .then(data => {
        if (data.error) {
            alert('Export failed: ' + data.error);
        } else {
            // 创建下载链接
            const dataStr = JSON.stringify(data, null, 2);
            const dataBlob = new Blob([dataStr], { type: 'application/json' });
            const url = URL.createObjectURL(dataBlob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `api_batch_export_${new Date().toISOString().split('T')[0]}.json`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);

            // 退出批量模式
            disableBatchExport();
        }
    })
    .catch(error => {
        alert('Export failed: ' + error.message);
    });
}
</script>
{% endblock %}